package com.nowcoder.community.controller;

import com.nowcoder.community.entity.DiscussPost;
import com.nowcoder.community.entity.Page;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.DiscussPostSerivce;
import com.nowcoder.community.service.LikeService;
import com.nowcoder.community.service.UserSerice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.nowcoder.community.util.CommunityConstant.ENTITY_TYPE_POST;

/**
 * @author ：LY
 * @date ：Created in 2021/1/18 22:21
 * @modified By：
 */
@Controller
public class HomeController {

    @Autowired
    private DiscussPostSerivce discussPostSerivce;

    @Autowired
    private UserSerice userSerice;

    @Autowired
    private LikeService likeService;

    @RequestMapping(path = "/",method = RequestMethod.GET)
    public String root(){
        return "forward:/index";
    }
    @RequestMapping(path = "/index",method = RequestMethod.GET)
    public String getIndexPage(Model model, Page page,@RequestParam(name = "ordermode",defaultValue = "0") int ordermode){
        //方法调用前，SpringMVC会自动实例化Model和Page 并奖Page注入Model
       //所以在thymeleaf就可以直接访问page对象的数据
        page.setRows(discussPostSerivce.findDiscussPostRows(0));
        page.setPath("/index?ordermode="+ordermode);
        List<DiscussPost> list = discussPostSerivce.findDiscussPosts(0, page.getOffset(), page.getLimit(),ordermode);
        List<Map<String,Object>> discussPosts = new ArrayList<>();
       if (list !=  null){
           for (DiscussPost discussPost : list) {
               Map<String,Object> map = new HashMap<>();
               map.put("post",discussPost);
               User user = userSerice.findUserById(discussPost.getUserId());
              map.put("user",user);
              long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST.getValue(),discussPost.getId());
              map.put("likeCount",likeCount);
               discussPosts.add(map);

           }
       }
        model.addAttribute("discussPosts",discussPosts);
       model.addAttribute("ordermode",ordermode);
        return "/index";
    }
    @GetMapping("/error")
    public String getErrorPage(){
        return "/error/500";
    }

    @GetMapping("/denied")
    public String getDeniedPage(){
        return "/error/404";
    }
}
